package com.cowealth.platform.common.base.util;

import com.cowealth.platform.common.base.adapter.CustomObjectTypeAdapter;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.lang.reflect.Type;

/**
 * Gson解析的工具类
 *
 * @author : skycdm
 * @version : 1.0.0
 * @date : 2020/7/1 15:05
 */
public class GsonUtils {

    private static Gson gson = null;
    static {
        gson = new Gson();
    }

    /**
     * json字符串转化为对象，重写Object相关的反序列化
     *
     * @param json
     * @param type
     * @return
     */
    public static <T> T fromJsonContainObj(String json, Type type) {
        Gson gson = new GsonBuilder()
                .registerTypeHierarchyAdapter(Object.class, new CustomObjectTypeAdapter()).create();

        return gson.fromJson(json, type);

    }

    /**
     * json字符串转化为对象，特殊处理日期格式
     *
     * @param json
     * @param type
     * @param format
     * @return
     */
    public static <T> T fromJsonContainDate(String json, Type type, String format) {
        Gson gson = new GsonBuilder()
                .setDateFormat(format)
                .create();

        return gson.fromJson(json, type);

    }


    /**
     * 一般默认的json字符串转化为对象
     *
     * @param json
     * @param type
     * @return
     */
    public static <T> T fromJson(String json, Type type) {
        return gson.fromJson(json, type);
    }

    /**
     * 一般默认的对象转化为json字符串
     *
     * @param json
     * @return
     */
    public static String toJson(Object obj) {
        return gson.toJson(obj);
    }

}
